package com.uinnova.product.eam.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.binary.core.exception.MessageException;
import com.uinnova.product.eam.comm.bean.DirCollaboratorInfo;
import com.uinnova.product.eam.comm.model.VcDiagramDir;
import com.uinnova.product.eam.service.IEamDirCollaboratorInfoSvc;
import com.uinnova.product.eam.service.es.IamsEsDirCollaboratorInfoSvc;
import com.uino.service.permission.microservice.IUserSvc;
import com.uino.dao.util.ESUtil;
import com.uino.util.sys.SysUtil;
import com.uino.bean.permission.base.SysUser;
import com.uino.bean.permission.query.CSysUser;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

@Deprecated
@Service
public class IamsEamDirCollaboratorInfoSvcImpl implements IEamDirCollaboratorInfoSvc {

    @Autowired
    private IUserSvc userSvc;

    @Autowired
    private IamsEsDirCollaboratorInfoSvc dirCollaboratorInfoSvc;


    @Override
    public List<JSONObject> findDirUserById(Long dirId, VcDiagramDir vcDiagramDir) {
        SysUser user = SysUtil.getCurrentUserInfo();
        try {
            if (vcDiagramDir == null) {
                //文件夹不存在
                throw MessageException.i18n("DMV_NOT_EXIST_FOLDER");
            }
            BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery().
                    must(QueryBuilders.termQuery("dirId", dirId));
            List<DirCollaboratorInfo> dirCollaboratorInfos = dirCollaboratorInfoSvc.getListByQuery(queryBuilder);
            List<String> coordinationUserCodeList = new ArrayList<>();
            Map<String,Integer> map = new HashMap<>();
            if (dirCollaboratorInfos != null) {
                dirCollaboratorInfos.forEach(dirCollaboratorInfo -> coordinationUserCodeList.add(dirCollaboratorInfo.getCoordinationUserCode()));
            }
            if (dirCollaboratorInfos != null) {
                dirCollaboratorInfos.forEach(dirCollaboratorInfo -> map.put(dirCollaboratorInfo.getCoordinationUserCode(),dirCollaboratorInfo.getPermissionLevel()));
            }
            if (!user.getLoginCode().equals(vcDiagramDir.getCreator()) && !coordinationUserCodeList.contains(user.getLoginCode())) {
                throw MessageException.i18n("没有协作权限");
            }

            CSysUser cdt = new CSysUser();
            cdt.setDomainId(user.getDomainId());
            List<SysUser> sysUserByCdt = userSvc.getSysUserByCdt(cdt);
            List<JSONObject> result = new ArrayList<>();
            sysUserByCdt.forEach(sysUser -> {
                String loginCode = sysUser.getLoginCode();
                if (!loginCode.equals(vcDiagramDir.getCreator())) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("userId", sysUser.getId());
                    jsonObject.put("userName", sysUser.getUserName());
                    jsonObject.put("userCode", sysUser.getLoginCode());
                    jsonObject.put("icon",sysUser.getIcon());
                    if (coordinationUserCodeList.contains(loginCode)) {
                        Integer permissionLevel = map.get(loginCode);
                        jsonObject.put("permissionLevel",permissionLevel);
                        jsonObject.put("isCoordination", true);
                    } else {
                        jsonObject.put("isCoordination", false);
                        jsonObject.put("permissionLevel",1);
                    }
                    result.add(jsonObject);
                }
            });
            return result;
        } catch (Exception e) {
            throw MessageException.i18n(e.getMessage());
        }
    }

    @Override
    public Boolean updateCooperation(Long dirId, List<JSONObject> userList, VcDiagramDir vcDiagramDir) {
        SysUser user = SysUtil.getCurrentUserInfo();
        if (vcDiagramDir == null) {
            //文件夹不存在
            throw MessageException.i18n("DMV_NOT_EXIST_FOLDER");
        }
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery().must(QueryBuilders.termQuery("dirId", dirId));
        List<DirCollaboratorInfo> dirCollaboratorInfos = dirCollaboratorInfoSvc.getListByQuery(queryBuilder);

        Map<String, DirCollaboratorInfo> coordinationMap = new HashMap<>();
        dirCollaboratorInfos.forEach(dirCollaboratorInfo -> coordinationMap.put(dirCollaboratorInfo.getCoordinationUserCode(), dirCollaboratorInfo));

        //校验用户是否有权限修改协作
        if (!user.getLoginCode().equals(vcDiagramDir.getCreator()) && !coordinationMap.containsKey(user.getLoginCode())) {
            throw MessageException.i18n("没有协作权限");
        }

        List<DirCollaboratorInfo> insertList = new ArrayList<>();
        List<Long> removeIds = new ArrayList<>();

        Map<String, JSONObject> userMap = new HashMap<>();
        userList.forEach((jsonObject -> userMap.put(jsonObject.getString("userCode"), jsonObject)));
        Set<String> userCodeSet = userMap.keySet();
        coordinationMap.forEach((userCode, coordination) -> {
            if (userCodeSet.contains(userCode)) {
                if(!coordination.getPermissionLevel().equals(userMap.get(userCode).getString("permissionLevel"))){
                    coordination.setPermissionLevel(userMap.get(userCode).getInteger("permissionLevel"));
                    dirCollaboratorInfoSvc.saveOrUpdate(coordination);
                    userCodeSet.remove(userCode);
                }else{
                    //包含，不做处理,
                    userCodeSet.remove(userCode);
                }
            } else {
                //不包含删除
                removeIds.add(coordination.getId());
            }
        });

        for (String userCode : userCodeSet) {
            DirCollaboratorInfo dirCollaboratorInfo = new DirCollaboratorInfo();
            dirCollaboratorInfo.setId(ESUtil.getUUID());
            dirCollaboratorInfo.setCoordinationUserCode(userCode);
            dirCollaboratorInfo.setPermissionLevel(userMap.get(userCode).getInteger("permissionLevel"));
            dirCollaboratorInfo.setDirId(dirId);
            //dirCollaboratorInfo.setPermissionLevel(OperateType.Write.getCode());
            dirCollaboratorInfo.setCreator(user.getLoginCode());
            dirCollaboratorInfo.setModifier(user.getLoginCode());
            dirCollaboratorInfo.setCreateTime(new Date());
            dirCollaboratorInfo.setModifyTime(new Date());
            insertList.add(dirCollaboratorInfo);
        }
        Integer inster = 0;
        if (!CollectionUtils.isEmpty(insertList)) {
            inster = dirCollaboratorInfoSvc.saveOrUpdateBatch(insertList);
        }
        Integer remove = 0;
        if (!CollectionUtils.isEmpty(removeIds)) {
            remove = dirCollaboratorInfoSvc.deleteByIds(removeIds);
        }
        return inster == 0 && remove == 0;
    }
}
